<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
    include "../../config.php";



    //获取服务器的数据，我这边开启的情况下就5秒刷新，不开启的话就每分钟一次好了
//获取服务器的数据，我这边开启的情况下就5秒刷新，不开启的话就每分钟一次好了
// ---------- 1. 基本配置 ----------
$statusUrls = [
    'http://host.arrow.enpingshi.com/traffic_status/format/json',
    'http://host.bat.enpingshi.com/traffic_status/format/json',
    'http://host.crossbow.enpingshi.com/traffic_status/format/json',
    'http://host.dagger.enpingshi.com/traffic_status/format/json',
    'http://host.spear.enpingshi.com/traffic_status/format/json'
];


// ---------- 2. 抓取并解码 ----------
$allData = [];
foreach ($statusUrls as $url) {
    $json = @file_get_contents($url);
    if ($json !== false) {
        $data = json_decode($json, true);
        if (isset($data['serverZones'])) {

            // 将服务器名称加上主机标识
            //去掉开头host，去掉结尾 enpingshi.com, 'http://host.spear.enpingshi.com/traffic_status/format/json'，只保留spear部分
            $server = str_replace([
                'http://host.',
                '.enpingshi.com/traffic_status/format/json'
            ],
                '',
                $url
            );
            $hostName = $server;

            foreach ($data['serverZones'] as $server => $zone)
            {
                //$allData[$hostName . '_' . $server] = $zone;
                $allData[$server] = $zone;
                $allData[$server]['host']  = $hostName;
            }


            //$allData调整排序，按照Sent的大小降序
            // 按照Sent（outBytes）大小降序排序
            uasort($allData, function($a, $b) {
                $aSent = isset($a['outBytes']) ? $a['outBytes'] : 0;
                $bSent = isset($b['outBytes']) ? $b['outBytes'] : 0;
                return $bSent - $aSent; // 降序排列
            });


        }
    }
}



// 如果没有获取到任何数据，则退出
if (empty($allData)) {
    exit("无法从任何服务器获取状态数据\n");
}






// ---------- 6. 循环插入 ----------
foreach ($allData as $server => $zone)
{
    $_data['ai_server']=$zone['host'];
    $_data['ai_zone_name']=$server;
    $_data['ai_request_counter']=$zone['requestCounter'];
    $_data['ai_in_bytes']=$zone['inBytes'];
    $_data['ai_out_bytes']=$zone['outBytes'];
    $_data['ai_responses_1xx']=$zone['responses']['1xx'];
    $_data['ai_responses_2xx']=$zone['responses']['2xx'];
    $_data['ai_responses_3xx']=$zone['responses']['3xx'];
    $_data['ai_responses_4xx']=$zone['responses']['4xx'];
    $_data['ai_responses_5xx']=$zone['responses']['5xx'];

    //执行语句
    $_sql=insert_data($table_prefix."dashboard_server_traffic",$_data);
    mysql_query($_sql) or die("Error: " . mysql_error().$_sql);
}

echo "同步完成，共写入/更新 " . count($allData) . " 条记录\n";



//    $_data['ai_browser']=$_REQUEST['browser'];
//    //执行语句
//    $_sql=insert_data($table_prefix."dashboard_browser_log",$_data);
//    mysql_query($_sql) or die("Error: " . mysql_error().$_sql);



?>

